package com.ruoyi.project.system.dispatch.service.impl;

import java.util.*;

import com.ruoyi.project.system.dispatch.domain.TaskCommentVo;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.service.IUserService;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.system.dispatch.mapper.VeDispatchMapper;
import com.ruoyi.project.system.dispatch.domain.VeDispatch;
import com.ruoyi.project.system.dispatch.service.IVeDispatchService;
import com.ruoyi.common.utils.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-01-29
 */
@Service
public class VeDispatchServiceImpl implements IVeDispatchService 
{
    @Autowired
    private VeDispatchMapper veDispatchMapper;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private IUserService userService;

    @Autowired
    private HistoryService historyService;

    /**
     * 查询【请填写功能名称】
     * 
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public VeDispatch selectVeDispatchById(Long id)
    {
        return veDispatchMapper.selectVeDispatchById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     * 
     * @param veDispatch 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<VeDispatch> selectVeDispatchList(VeDispatch veDispatch)
    {
        return veDispatchMapper.selectVeDispatchList(veDispatch);
    }

    /**
     * 新增【请填写功能名称】
     * 
     * @param veDispatch 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertVeDispatch(VeDispatch veDispatch)
    {
        return veDispatchMapper.insertVeDispatch(veDispatch);
    }

    /**
     * 修改【请填写功能名称】
     * 
     * @param veDispatch 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateVeDispatch(VeDispatch veDispatch)
    {
        return veDispatchMapper.updateVeDispatch(veDispatch);
    }

    /**
     * 批量删除【请填写功能名称】
     * 
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteVeDispatchByIds(String ids)
    {
        return veDispatchMapper.deleteVeDispatchByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除【请填写功能名称】信息
     * 
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteVeDispatchById(Long id)
    {
        return veDispatchMapper.deleteVeDispatchById(id);
    }

    @Override
    @Transactional
    public int submit(Long id, Long userId) {
        VeDispatch veDispatch=veDispatchMapper.selectVeDispatchById(id);
        String processDefikey="ApplyProcess";
        Map<String, Object> variables = new HashMap<String,Object>();
        variables.put("inputUser1", userId);
        variables.put("inputUser2", 4);
        //ProcessEngine processEngine= ProcessEngines.getDefaultProcessEngine();

        if(veDispatch.getStatus()==0){
            ProcessInstance pi = runtimeService.startProcessInstanceByKey(processDefikey, variables);
            veDispatch.setFlowInstantId(Long.parseLong(pi.getProcessInstanceId()));
            veDispatch.setStatus((long) 2);//状态(0-未提交，1-打回，2-审核中，3-已完成）
            TaskQuery taskQuery = taskService.createTaskQuery();
            // 办理人的任务列表
            List<Task> list = taskQuery
                    .taskAssignee(""+userId)
                    .processInstanceId(pi.getProcessInstanceId())
                    .list();
            Task task=list.get(0);
            taskService.complete(task.getId());

            return  veDispatchMapper.updateVeDispatch(veDispatch);
        }
        else{
            Long flowInstantId=veDispatch.getFlowInstantId();
            TaskQuery taskQuery = taskService.createTaskQuery();
            // 办理人的任务列表
            List<Task> list = taskQuery
                    .processInstanceId("" + flowInstantId)
                    .list();
            Task task=list.get(0);
            taskService.complete(task.getId());
            veDispatch.setStatus((long) 2);//状态(0-未提交，1-打回，2-审核中，3-已完成）
            return veDispatchMapper.updateVeDispatch(veDispatch);
        }
//        ProcessInstance pi =runtimeService
//                .startProcessInstanceByKey(processDefikey,variables);
//        veDispatch.setFlowInstantId(Long.parseLong(pi.getProcessInstanceId()));
//        veDispatch.setStatus((long) 1);//状态(0-未提交,1-已提交,2-审核中,3-已完成)
//        return veDispatchMapper.updateVeDispatch(veDispatch);
    }


    @Override
    public List<VeDispatch> noFinishTask(Long userId,String processDefiniionKey) {
        List<VeDispatch> veDispatchList=new ArrayList<VeDispatch>();
        // 创建一个任务查询对象
        TaskQuery taskQuery = taskService.createTaskQuery();
        // 办理人的任务列表
        List<Task> list = taskQuery
                .taskAssignee(""+userId)
                .processDefinitionKey(processDefiniionKey)
                .list();
        // 遍历任务列表
        if (list != null && list.size() > 0) {
            for (Task task : list) {
//                if(!task.getName().equals("提交申请")){
                Long flowInstanceId= Long.parseLong(task.getProcessInstanceId());
                //根据流程id查询学生mapper的方法
                VeDispatch veDispatch=veDispatchMapper.selectVeDispatchFlowId(flowInstanceId);
                veDispatchList.add(veDispatch);
//                }

            }
        }
        return veDispatchList;
    }

    @Override
    public void completeTask(Long flowInstantId, Integer agree,Long userId,String comment,Long id) {

        TaskQuery taskQuery = taskService.createTaskQuery();

        VeDispatch veDispatch=veDispatchMapper.selectVeDispatchById(id);
        // 办理人的任务列表
        List<Task> list = taskQuery
                .processInstanceId("" + flowInstantId)
                .list();
        // 遍历任务列表
        Map<String, Object> params = new HashMap<String, Object>();
        if (list != null && list.size() > 0) {
            for (Task task : list) {
                if(task.getName().equals("部门负责人审批")){
                    //params.put("pass2", agree);
                    if(agree==1){
                        params.put("inputUser3",5);
                        veDispatch.setStatus((long) 2);
                    }else veDispatch.setStatus((long) 1);
                    params.put("pass",agree);
                        //sstudent.setStatus((long) 3);
                    //else sstudent.setStatus((long) 1);
                }else{
                    params.put("pass1",agree);
                    if(agree==1)
                        veDispatch.setStatus((long) 3);
                    else veDispatch.setStatus((long) 1);
                }
                veDispatchMapper.updateVeDispatch(veDispatch);
                // 添加批注时候的审核人，通常应该从session获取
                Authentication.setAuthenticatedUserId(userId.toString());

                // 添加批注
                taskService.addComment(task.getId(), task.getProcessInstanceId(), comment);

                // taskId：任务id
                taskService.complete(task.getId(), params);
            }
        }
    }

    @Override
    public List<TaskCommentVo> getTaskCommentList(Long flowInstantId) {
        List<TaskCommentVo> taskCommentVoList=new ArrayList<>();

        List<Comment> list = new ArrayList();

        //从历史批注中取数据
        list = taskService.getProcessInstanceComments(""+flowInstantId);

        for (Comment com : list) {
            TaskCommentVo taskCommentVo=new TaskCommentVo();
            taskCommentVo.setMessage(com.getFullMessage());

            User user=userService.selectUserById(Long.parseLong(com.getUserId()));
            taskCommentVo.setUserName(user.getUserName());


            //从历史任务取数据
            List<HistoricTaskInstance> hist= historyService.createHistoricTaskInstanceQuery()
                    .processInstanceId(""+flowInstantId)
                    .taskId(com.getTaskId())
                    .list();
            if(hist!=null&&hist.size()>0){
                HistoricTaskInstance historicTaskInstance=hist.get(0);
                taskCommentVo.setTaskKeyId(historicTaskInstance.getTaskDefinitionKey());
                taskCommentVo.setTaskName(historicTaskInstance.getName());
            }
            taskCommentVoList.add(taskCommentVo);
        }


        //排序
        List<TaskCommentVo> taskCommentVoListSort=new ArrayList<>();
        for(int i= taskCommentVoList.size()-1;i>=0;i--)
        {   TaskCommentVo temp=taskCommentVoList.get(i);
            taskCommentVoListSort.add(temp);
        }
        return taskCommentVoListSort;
    }

    @Override
    public List<VeDispatch> finishTask(Long userId,String processDefiniionKey) {
        List<VeDispatch> listFinishVeDispatch=new ArrayList<VeDispatch>();
        List<HistoricTaskInstance> list =historyService
                .createHistoricTaskInstanceQuery()
                .taskAssignee(userId.toString())
                .processDefinitionKey(processDefiniionKey)
                .processFinished()
                .list();
        if(list!=null&&list.size()>0){
            for(HistoricTaskInstance temp:list){
                Long flowInstantId=Long.parseLong(temp.getProcessInstanceId());
                VeDispatch veDispatch=veDispatchMapper.selectVeDispatchFlowId(flowInstantId);
                listFinishVeDispatch.add(veDispatch);
            }
        }
        //去重
        List<VeDispatch> listFinishVeDispatch1= new ArrayList<>(new HashSet<>(listFinishVeDispatch));
        return listFinishVeDispatch1;
    }
}
